/*
 * @Author: 元辰
 * @Date: 2023-06-28 14:33:02
 * @LastEditTime: 2023-06-28 17:12:01
 * @LastEditors: 元辰
 */
const fs = require('fs');

const addMapping = (router, mapping) => {
  for (let url in mapping) {
    if (url.startsWith('GET ')) {
      const path = url.substring(4);
      router.get(path, mapping[url]);
    } else if (url.startsWith('POST ')) {
      const path = url.substring(5);
      router.post(path, mapping[url]);
    } else if (url.startsWith('PUT ')) {
      const path = url.substring(4);
      router.put(path, mapping[url]);
    } else if (url.startsWith('DELETE ')) {
      const path = url.substring(7);
      router.del(path, mapping[url]);
    } else {
      console.log(`invalid URL: ${url}`);
    }
  }
}

const addControllers = (router, dir) => {
  const __dirname = '/Users/admin/Documents/learn/eOurs-api';

  fs.readdirSync(__dirname + '/' + dir).filter((f) => {
    return f.endsWith('.js');
  }).forEach((f) => {
    const mapping = require(__dirname + '/' + dir + '/' + f);
    addMapping(router, mapping);
  });
}

module.exports = (dir) => {
  const controllers_dir = dir || 'controllers';
  const router = require('koa-router')();

  addControllers(router, controllers_dir);

  router.prefix('/api');

  return router.routes();
};